// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2021 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------

import {
	HEADER,
	TOKENNAME
} from '@/config/app';
import {
	toLogin,
	checkLogin
} from '../libs/login';
import { UID } from '@/config/cache';
import Cache from '@/utils/cache';

import store from '../store';


/**
 * 发送请求
 */
function baseRequest(url, method, data, {
	noAuth = false,
	noVerify = false
}) {
	let Url = 'https://xcx.arzanbaza.cn',
		header = HEADER;
	if (process.env.NODE_ENV === 'development') {
		Url = 'https://h5.kaixikeji.cn';
		console.log('开发环境');
	} else {
		Url = 'https://xcx.arzanbaza.cn';
		console.log('生产环境');
	}
	if (!noAuth) {
		//登录过期自动登录
		if (!store.state.app.token && !checkLogin()) {
			toLogin();
			return Promise.reject({
				msg: '未登录'
			});
		}
	}
	if (store.state.app.token) header[TOKENNAME] = 'Bearer ' + store.state.app.token;

	return new Promise((reslove, reject) => {
		uni.request({
			url: Url + '/Api/' + url,
			method: method || 'GET',
			header: header,
			data: {
				...data,
				userId: Cache.get(UID)
			},
			success: (res) => {
				console.log(res)
				if (noVerify) {
					reslove(res.data, res);
				} else if (res.data.code == 1) {
					reslove(res.data, res);
				} else if (res.data.code === 2) {
					toLogin();
					reject(res.data);
				} else if (res.data.code == 0) {
					uni.showModal({
						title: 'ئەسكەرتىش',
						content: res.data.msg,
						showCancel: false,
						confirmText: 'ok'
					});
					reject(res.data.msg);
				} else {
					reject(res.data.msg || '系统错误');
				}
				uni.hideLoading();
			},
			fail: (msg) => {
				let data = {
					mag: '请求失败',
					status: 1 //1没网
				}
				// #ifdef APP-PLUS
				reject(data);
				// #endif
				// #ifndef APP-PLUS
				reject('请求失败');
				// #endif
			}
		})
	});
}

const request = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
	request[method] = (api, data, opt) => baseRequest(api, method, data, opt || {})
});



export default request;
